package fun.hijklmn.magic.resource.server.controller;

import fun.hijklmn.magic.common.enums.ResponseCodeEnum;
import fun.hijklmn.magic.resource.common.transport.UploadFileRequest;
import fun.hijklmn.magic.resource.common.transport.UploadFileResponse;
import fun.hijklmn.magic.resource.server.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Description
 * @Author fs
 * @Date 2021/5/25 16:35
 * @Version 0.0.1-SNAPSHOT
 **/
@Slf4j
@RestController
public class UploadController {

    @Autowired
    private UploadService uploadService;

    @PostMapping(value = "upload")
    public UploadFileResponse upload(UploadFileRequest uploadFileRequest) {
        return uploadService.upload(uploadFileRequest);
    }

    @PostMapping(value = "uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public UploadFileResponse uploadFile(@RequestParam("key") String key, @RequestParam("fileName") String fileName, @RequestPart("file") MultipartFile file) {

        UploadFileRequest uploadFileRequest = new UploadFileRequest();
        uploadFileRequest.setKey(key);
        uploadFileRequest.setFileName(fileName);

        try {
            uploadFileRequest.setInputStream(file.getInputStream());
            return uploadService.upload(uploadFileRequest);
        } catch (IOException e) {
            log.error("---------->上传图片失败", e);
        }

        UploadFileResponse uploadFileResponse = new UploadFileResponse();
        uploadFileResponse.setCode(ResponseCodeEnum.ERROR.code());
        uploadFileResponse.setMessage("上传失败");
        return uploadFileResponse;

    }

}
